package com.cloud.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cloud.common.constants.DataTableFields;
import com.cloud.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis_plus 字段自动填充/修改拦截
 *
 * @author yzj
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 添加元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(DataTableFields.Mybatis_CreateBy)) {
            this.setFieldValByName(DataTableFields.Mybatis_CreateBy, SecurityUtils.getUserName(), metaObject);
        }
        if (metaObject.hasSetter(DataTableFields.Mybatis_CreateTime)) {
            this.setFieldValByName(DataTableFields.Mybatis_CreateTime, new Date(), metaObject);
        }
        if (metaObject.hasSetter(DataTableFields.deleted)) {
            this.setFieldValByName(DataTableFields.deleted, 0, metaObject);
        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtils.isEmpty(this.getFieldValByName(DataTableFields.Mybatis_UpdateBy, metaObject))) {
            this.setFieldValByName(DataTableFields.Mybatis_UpdateBy, SecurityUtils.getUserName(), metaObject);
        }
        if (ObjectUtils.isEmpty(this.getFieldValByName(DataTableFields.Mybatis_UpdateTime, metaObject))) {
            this.setFieldValByName(DataTableFields.Mybatis_UpdateTime, new Date(), metaObject);
        }
    }

}
